/* 
 * 全局权限验证守卫，用于验证用户登录
 *
*/

import { Injectable, CanActivate, HttpException, HttpStatus, ExecutionContext, } from '@nestjs/common';
//import * as Redis from 'ioredis';
import { from } from 'rxjs';

//const redis = new Redis;
@Injectable()
export class AuthGuard implements CanActivate {

  // context 请求的(Response/Request)的引用
  async canActivate(context: ExecutionContext): Promise<boolean> {

    // 获取请求对象
    const request = context.switchToHttp().getRequest();
    // 获取请求头中的token字段
    const token = request.headers.authorization;
    // 把token放到参数里
    request.body.authorization=token;
    // 如果白名单内的路由就不拦截直接通过
    if (this.hasUrl(this.urlList, request.url)) {
      return true;
    }
    // const hasToken=await redis.get(token).then(function (result) {
    //   // 验证token的合理性以及根据token做出相应的操作
    //   return result?true:false;
    // });
    const hasToken=true;
    if(hasToken) {
      try {
        // 这里可以添加验证逻辑
        return true;
      } catch (e) {
        throw new HttpException(
          '授权方式过期,请先登录',
          HttpStatus.UNAUTHORIZED,
        );
      }
    } else {
      throw new HttpException(
        '没有授权访问,请先登录',
        HttpStatus.UNAUTHORIZED,
      );
    }

  };
  
  // 白名单数组
  private urlList: string[] = [
    '/test',
    '/files/img',
    '/auth/login',
    '/'
  ];

  // 验证该次请求是否为白名单内的路由
  private hasUrl(urlList: string[], url: string): boolean {
    let flag: boolean = false;
    let _url = url.indexOf('?') >= 0 ? url.substr(0, url.indexOf('?')) : url;
    if (urlList.indexOf(_url) >= 0) {
      flag = true;
    }
    return flag;
  }
};
